<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索案例</title>
    <style>
      ul {
        list-style-type: disc;
      }
    </style>
  </head>
  <div id="app">
    <h1>{{msg}}</h1>
    搜索姓名:<input type="text" placeholder="请输入搜索关键字" v-model:value="keyWord">
    <button @click="sortType=1">按年龄升序</button>
    <button @click="sortType=2">降序</button>
    <button @click="sortType=0">按年龄原来顺序</button>
    <ul v-for="(item,index) in copyArr" :key="index">
      <li>{{item}}</li>
    </ul>
  </div>

  <body>

  </body>
  <script src="../js/vue.js"></script>
  <script>
    const vm = new Vue({
      el: "#app",
      data: {
        msg: "列表渲染搜索案例",
        arr: [{
          name: '马冬梅',
          age: 59,
          gender: 'female'
        }, {
          name: '周冬雨',
          age: 25,
          gender: 'female'
        }, {
          name: '周杰伦',
          age: 66,
          gender: 'male'
        }, {
          name: '桂伦镁',
          age: 39,
          gender: 'female'
        }],
        keyWord: '',
        //排序方式 0代表默认，1代表升序,2代表降序
        sortType: 0
      },
      computed: {
        copyArr: function () {
          const {
            arr,
            keyWord
          } = this;
          // 1.搜索过滤
          let copyArr = arr.filter((item, index) => {
            return item.name.indexOf(keyWord) !== -1;
          })

          // 2.搜索排序
          if (this.sortType !== 0) {
            console.log(this.sortType);
            copyArr.sort((a, b) => {
              if (this.sortType == 1) {
                return a.age - b.age
              } else {
                return b.age - a.age
              }
            })
          }

          return copyArr
        }
      },
    })
  </script>

</html>